<template>
	<view class="page-container">
		<use-navbar ref="navbar" type="custom" :show="showNavbar" :back="false" :bg-color="navbarBgcolor" :title="''">

			<template v-slot:title>
				<view class="tac">
					<text class="fs-34 fwbd ft-white">事项</text>
				</view>
			</template>
			<template v-slot:right>
				<view class="tac trophy" @click='toTrophy'>
					<image src="../../static/icons/icon-trophy.png" class="icon"></image>
				</view>
			</template>
		</use-navbar>
		<web-view  style="position: fixed;top:0;left: 0;width: 100vw;height: 100vh;"
		src="https://mcda.youerp.cn/web/IndexScene/index.html" full-screen></web-view>
		<!-- #ifdef  APP-PLUS || MP-WEIXIN || H5 -->
		<view>
			<view class="container">
				<!-- <use-waterfalls></use-waterfalls> -->
			</view>
			<view class="dflex" style="flex-wrap: wrap;">
				<view v-for="(item,index) in dataList" :key="index" class="wpre-50">
					<use-matter-item :item='item' :type="item.customstyle.shape"
						@clickItem='clickMItem'></use-matter-item>
				</view>
			</view>
			<!-- <grid-layout :layout="dataList" :col-num="2" :row-height="10" :is-draggable="true" :is-resizable="true"
				:is-mirrored="false" :vertical-compact="true" :margin="[0, 0]" :use-css-transforms="true"
				@layout-updated="layoutUpdatedEvent">
				<grid-item v-for="item in dataList" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i"
					:key="item.i">
					<use-matter-item :item='item' :type="item.customstyle.shape"
						@clickItem='clickMItem'></use-matter-item>
				</grid-item>
			</grid-layout> -->
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<!-- #endif -->
		<use-popup mode="bottom" bgclass=" " :show="operateShow" :zIndex='999' @open='openPopup'
			@close="closePopup('')">
			<view class="share-area margin border-radius bg-main">
				<view class="matterType dflex leftFlex">
					<view class="item dflex-c u-flex-col" v-for="(item, index) in matterType" :key="index"
						@click="goToPage('btn',item)">
						<image mode="aspectFit" :src="item.src"></image>

						<text>{{ item.type }}</text>
					</view>
				</view>
			</view>
		</use-popup>
	</view>
	<!-- 普通弹窗 -->
	<uni-popup ref="popup" background-color="#fff" @change="change">
		<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }"><text
				class="text">popup 内容</text></view>
	</uni-popup>
	<movable-area
		style="height: 90vh; width: 100%;position: fixed;top:50px;left: 0;bottom:60px ;pointer-events: none;z-index: 95;">
		<movable-view :x="screen.x" :y="screen.y" direction="all"
			style="width: 45vw; height: 55px;pointer-events: auto;">
			<view class="button-3d" @click="fabClick('new')" style="width: 45vw;">
				<span class="button-3d-shadow"></span>
				<span class="button-3d-edge"></span>
				<span class="button-3d-front text tac">记一笔</span>
			</view>
		</movable-view>
	</movable-area>
	<use-tabbar></use-tabbar>
</template>

<script setup>
	// --组合式 API 模板
	import {
		ref,
		reactive,
		computed,
		onMounted,
		getCurrentInstance
	} from 'vue'

	import {
		storeToRefs
	} from 'pinia';
	import {
		useUserStore
	} from '@/store'
	import {
		onLoad,
		onShow,
		onBackPress
	} from "@dcloudio/uni-app";
	const {
		ctx,
		proxy
	} = getCurrentInstance();
	console.log("ctx", ctx);
	console.log("proxy", proxy.$config);
	let UserStore = useUserStore();

	const navbarHeight = ref('0')
	const statusHeight = ref('0')
	const navbarBgcolor = ref('#46a7f1')
	const hasPermissions = ref(true)
	const empty = ref(false)
	const allDataList = ref([])
	const dataList = ref([])
	// 加载更多状态
	const loadmoreType = ref('more')
	// 请求数据
	const reqdata = ref({
		page: 1,
		rows: 50,
		sidx: 'sort',
		sord: 'asc'
	})
	const operateShow = ref(false)
	const popupShow = ref('')
	const active = ref(0);

	const showFilterPopup = ref(false)
	onLoad((option) => {
		console.log("B 页面 onLoad:", option);
		uni.hideTabBar();
	});

	onShow(() => {
		console.log("B 页面 onShow");
		uni.showLoading({})
		loadData('add', 1);
		checkPermissions();
	});
	const backHome = () => {
		uni.navigateTo({
			url: '/pages/tabbar/launch'
		});
	}
	const clickMItem = () => {
		console.log("点击了")
	}
	const scroll = function() {}
	const gotoSearch = function() {
		uni.navigateTo({
			url: `/pages/search/search?type=` + tabState.value.list[
				tabState.current] + `&title=事项查询`
		});
	}
	const goToPage = async function(type, item) {
		let _check = await checkLoginState();
		console.log("结果：", _check);
		if (!_check) {
			return;
		}
		let __check = await checkUserPermissions();
		console.log("权限结果：", __check);
		if (!__check) {
			return;
		}
		uni.navigateTo({
			url: item.url
		});
		proxy.$utils.timerout(() => {
			operateShow.value = false;
		}, 250)
	}
	const toMessage = () => {
		uni.navigateTo({
			url: '/pages/tabbar/message'
		});
	}
	const fabClick = (type) => {
		setTimeout(() => {
			uni.navigateTo({
				url: `/pages/matter/new?id=&type=${type}`
			});
		}, 350)
	}
	const openPopup = (state) => {}
	const closePopup = (type) => {
		operateShow.value = false
	}

	const upper = function() {}
	const lower = function() {}
	const loadData = (type = 'add', loading) => {
		if (!UserStore.islogin) {
			uni.hideLoading()
			return;
		}
		if (loadmoreType === 'loading') {
			// 防止重复加载
			return;
		}
		if (loading == 1 || type == 'refresh') {
			// 从首页开始加载
			reqdata.page = 1;
		}
		// 没有更多直接返回 
		if (type === 'add') {
			if (loadmoreType === 'nomore') {
				return;
			}
			// 加载中
			loadmoreType.value = 'loading';
		} else {
			// 更多
			loadmoreType.value = 'more'
		}

		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: {
				storedPro: 'P_SaaS_MCDA_List',
				paraNum: 1,
				resultSetNum: 1,
				para1: UserStore.member.member_id
			}
		}
		console.log(params)
		try {
			proxy.$api.getData(url, params).then((res) => {
				console.log("事项列表", res)
				if (res.status == '1') {
					if (loading == 1 || type == 'refresh') {
						allDataList.value = [];
					}
					let datas = res.data1;
					datas.forEach((x, i) => {
						const numbers = [3, 4, 5];
						const randomIndex = Math.floor(Math.random() * numbers.length);
						const randomNumber = numbers[randomIndex];
						let _pos = getPosition(i);
						console.log(_pos, _pos[0], _pos[1])
						datas[i].title = x.name;
						datas[i].x = _pos[0];
						datas[i].y = _pos[1];
						datas[i].w = randomNumber;
						datas[i].h = 12;
						datas[i].i = i.toString();
					})
					console.log(datas);
					datas = fmtRandomShape(datas);
					if (datas && datas.length > 0) {
						let _datas = datas;
						dataList.value = datas;
						allDataList.value = [...allDataList.value, ..._datas];
						if (datas.length >= reqdata.rows) {
							reqdata.page++;
							loadmoreType.value = 'more'
						} else {
							loadmoreType.value = 'nomore'
						}
					} else {
						loadmoreType.value = 'nomore'
						allDataList.value = []
						dataList.value = []
					}
					console.log(dataList.value)
					empty.value = dataList.length === 0;

				}

				if (loading == 1) {
					proxy.$utils.timerout(() => {
						uni.hideLoading()
					}, 250)
				} else if (type == 'refresh') {
					uni.stopPullDownRefresh();
				}
			})
		} catch (e) {
			console.log(e)
		}
	}
	// -检测用户缓存的登录信息
	const checkLoginState = async () => {
		return true;
		if (!UserStore.islogin) {
			proxy.$utils.timerout(() => {
				proxy.$utils.alert('请先登录系统~', function(bool) {

				}, false)
			}, 150)
			return false;
		} else {
			if (!UserStore.member.member_weixin) {
				proxy.$utils.timerout(() => {
					showAuthorize.value = true;
				}, 150)
				return false;
			}
			proxy.$utils.timerout(() => {
				showAuthorize.value = false;
			}, 250)
			return true;
		}
	}
	// 权限判断，需做调整？？？
	const checkPermissions = () => {
		console.log(UserStore.member)
		if (UserStore.member.member_rid == '999' || !UserStore.member.member_rid) {
			hasPermissions.value = false;
		} else {
			hasPermissions.value = true;
		}
	}
	// -检测用户操作权限
	const checkUserPermissions = async () => {
		return true;
	}
	const randomNum = () => {
		const randomNumber = Math.floor(Math.random() * 4) + 1;
		console.log(randomNumber);
		return randomNumber;
	}

	const getRandomColor = () => {
		const min = 1;
		const max = 7;
		const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
		return colors.value[randomNum]; // 拼接 RGB 字符串
	}
	const UnreadMsg = computed(() => {
		console.log(UserStore.msgnum)
		return parseInt(UserStore.msgnum)
	})
	const baseUrl = computed(() => {
		return proxy.$config.baseTestUrl
	})
	const screen = computed(() => {
		return {
			x: UserStore.systemInfo.screenWidth +50,
			y: UserStore.systemInfo.screenHeight - 200
		}
	})
	const showNavbar = computed(() => {
		return true;
		// --return UserStore.systemInfo.terminal == 'windows' ? false : true;
	})
	onMounted(() => {
		console.log(new Date())
	})


	// 使用 vue3 setup 语法糖
	const layout = reactive([{
			x: 0,
			y: 0,
			w: 5,
			h: 6,
			i: "0"
		},
		{
			x: 1,
			y: 0,
			w: 5,
			h: 8,
			i: "1"
		}
	]);
	const layoutUpdatedEvent = (newLayout) => {
		console.log("Created layout: ", newLayout)
	}
	// 定义不同的形状、颜色和大小
	const colors = ref([
		'#888888', '#BBBB00', '#007799', '#550088', '#FFA07A', '#B8860B', '#006400', '#1E90FF', '#00AA00'
	])

	const totalWidth = ref(414)
	totalWidth.value = UserStore.systemInfo.screenWidth || 414;
	// 正方形--square   椭圆形的--elliptic
	const shapes = ref(['square', 'circle', 'egg', 'elliptic'])
	const fmtRandomShape = (list) => {
		console.log(list);
		list.forEach((x, i) => {
			let _layout = generateLayout(i);
			if (i % 2 !== 0) {
				console.log(i);
			}
			console.log(_layout);
			list[i].customstyle = _layout;
		})
		list.forEach((x, i) => {
			if (i % 2 !== 0 && i !== 0) {
				list[i].customstyle.width = totalWidth.value - list[i - 1].customstyle.width;
			}
		})
		console.log(list);
		return list;
	}

	const getRandomElement = (array) => {
		const index = Math.floor(Math.random() * array.length);
		return array[index];
	}
	const generateLayout = (i) => {
		let remainingShapes = [...shapes.value];

		if (remainingShapes.length === 0) {
			remainingShapes = [...shapes.value];
		}

		const rowItems = [];
		const shape1 = getRandomElement(remainingShapes);
		remainingShapes.splice(remainingShapes.indexOf(shape1), 1);

		const shape2 = getRandomElement(remainingShapes);
		remainingShapes.splice(remainingShapes.indexOf(shape2), 1);

		const color1 = getRandomElement(colors.value);
		let color2 = getRandomElement(colors.value);
		while (color2 === color1) {
			color2 = getRandomElement(colors.value);
		}
		let width1 = 0;
		if (i % 2 === 0) {
			width1 = Math.random() * (totalWidth.value - 200) + 100;
		} else {
			width1 = 0;
		}
		return ({
			shape: shape1,
			color: color1,
			width: width1
		});


	}
	const getPosition = (number) => {
		const row = Math.floor(number / 2);
		const col = number % 2;
		return [row, col];
	}
</script>

<style lang="scss">
	page,
	.page-container {
		min-height: 100vh;
		background: $uni-bg-color-grey;
	}

	.content {
		height: 100%;
		position: relative;
	}

	.matterType {
		padding: 16px 0 26px 0;

		.item {
			width: 25%;

			image {
				width: 48px;
				height: 48px;
			}

			text {
				line-height: 1;
				font-size: 14px;
				color: #999;
				margin-top: 6px;
			}
		}
	}

	.area {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 999;
		pointer-events: none;
	}

	.area .view {
		width: auto;
		height: auto;
		pointer-events: auto;
	}

	.area .view .icon {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		overflow: hidden;
		position: relative;
		box-shadow: 1px 2px 4px 2px rgba(0, 0, 0, 0.25);
		background-color: rgba(255, 255, 255, 0.9);
	}

	.area .view image {
		width: 100%;
		height: 100%;
	}

	.triangle-popup {
		overflow: visible;
		background-color: rgba(38, 38, 38, 1.0);

		&:before {
			right: 12px;
			bottom: auto;
			position: absolute;
			top: -15px;
			width: 0;
			height: 0;
			border: 8px solid;
			content: '';
			border-color: transparent transparent rgba(52, 52, 52, 1.0) transparent;
		}
	}

	.box-shadow {
		box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.25);
	}

	.uni-list-item {
		border-bottom: 1px solid #e5e5e5;
	}

	.grid-item {
		display: flex;
		align-items: center;
		justify-content: center;
		border: solid #ccc 1px;
		background-color: #ccc;
	}
</style>